package hotel.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import hotel.entity.Category;
import hotel.entity.ItemDescription;
import hotel.entity.Payment;
import hotel.entity.Room;
import hotel.entity.Sales;
import hotel.entity.SalesLineItem;
import hotel.service.ICategoryService;
import hotel.service.IRoomService;
import hotel.service.ISalesLineItemService;
import hotel.service.ISalesService;
import hotel.service.IitemDescriptionService;
import util.HqlUtil;
import util.JSONUtil;

@Controller
public class SalesController {

	@Autowired
	ICategoryService<Category> categoryService;
	@Autowired
	IRoomService<Room> roomService;
	@Autowired
	ISalesService<Sales> salesService;
	@Autowired
	ISalesLineItemService<SalesLineItem> itemService;
	@Autowired
	IitemDescriptionService<ItemDescription> descService;
	
	//checkin
	@RequestMapping(value="checkinManagement")
	public String checkinManage(Model model) {
		model.addAttribute("categoryList", categoryService.listAll("Category"));
		return "checkin/checkinlist";
	}
	
	@ResponseBody
	@RequestMapping(value="checkinlist")
	public String checkinList(Model model,int page,int limit,HttpServletRequest request) {
		String json=null;
		String op=request.getParameter("op");
		if(op!=null&&op.equals("search")) {//表单搜索
			//根据表单参数组装hql语句
			String hql=HqlUtil.assembleHqlForCheckinForm(request.getParameterMap());
			List<SalesLineItem> list=itemService.list(hql);
			if(list==null) {
				json="{\"code\": 0,\"msg\":\"success\",\"count\": 0,\"data\":[]}";
			}
			else {
				json=JSONUtil.checkinListToJson(list);
				json="{\"code\": 0,\"msg\":\"success\",\"count\": "+list.size()+",\"data\":"+json+"}";	
			}
		}else {
			int totalCount=itemService.getCheckinCount();
			int firstResult=(page-1)*limit;
			json=JSONUtil.checkinListToJson(itemService.paging(firstResult, limit));
			json="{\"code\": 0,\"msg\":\"success\",\"count\": "+totalCount+",\"data\":"+json+"}";
		}
		return json;
	}
	
	@RequestMapping(value="makeNewSale",method=RequestMethod.GET)
	public String makeNewSale(Model model) {
		model.addAttribute("categoryList", categoryService.listAll("Category"));
		return "checkin/add";
	}
	
	@ResponseBody
	@RequestMapping(value="endSale",method=RequestMethod.POST)
	public String endSale(Sales sales,Payment payment,HttpServletRequest request) {
		List<SalesLineItem> salesLineItemList=new ArrayList<SalesLineItem>();
		String[] counts=request.getParameterValues("count");
		String[] customerNames=request.getParameterValues("customerName");
		String[] id_numbers=request.getParameterValues("id_number");
		String[] teles=request.getParameterValues("tele");
		String[] roomids=request.getParameter("roomids").split(",");
		double price=Double.parseDouble(request.getParameter("price"));
		
		for(int i=0;i<sales.getAmount();i++) {
			SalesLineItem item=new SalesLineItem();
			int count=Integer.parseInt(counts[i]);
			item.setCount(count);
			Room room=new Room();
			room.setRoomid(Integer.parseInt(roomids[i]));
			item.setRoom(room);
			item.setPrice(price);
			salesLineItemList.add(item);
			
			String[] temp_name=customerNames[i].split(",");
			String[] temp_number=id_numbers[i].split(",");
			String[] temp_tele=teles[i].split(",");
			for(int j=0;j<count;j++) {
				ItemDescription desc=new ItemDescription();
				desc.setCustomerName(temp_name[j]);
				desc.setId_number(temp_number[j]);
				desc.setTele(temp_tele[j]);
				item.getDescriptions().add(desc);
				//desc.setSalesLineItem(item);
			}
		}
		
		if(salesService.save(sales, salesLineItemList,payment))
			return JSONUtil.returnSuccess();
		else
			return JSONUtil.returnFailure();
	}
	
	/**
	 * 选择房间
	 */
	@RequestMapping(value="selectRoom")
	public String selectRoom(Model model,int categoryid,int amount) {
		model.addAttribute("category", categoryService.findById(Category.class, categoryid));
		model.addAttribute("roomList", roomService.findRoomByCategory(categoryid));
		model.addAttribute("availableMap", roomService.findAvailableRoomByCategory(categoryid));
		model.addAttribute("amount", amount);
		return "checkin/selectRoom";
	}
	
	/**
	 * 入住登记-填写住户信息
	 */
	@RequestMapping(value="enterItem")
	public String enterItem(Model model,int divId) {
		model.addAttribute("divId", divId);
		return "checkin/checkin_customer";
	}
	
	//checkout
	@ResponseBody
	@RequestMapping(value="checkout")
	public String checkout(int itemid) {
		if(itemService.checkout(itemid))
			return JSONUtil.returnSuccess();
		return JSONUtil.returnFailure();
	}
	
	/**
	 * 销售记录
	 */
	@RequestMapping(value="salesManagement")
	public String salesManagement() {
		return "sales/saleslist";
	}
	
	@ResponseBody
	@RequestMapping(value="saleslist")
	public String salesList(Model model,int page,int limit) {
		String json=null;
		int totalCount=salesService.getSalesCount();
		int firstResult=(page-1)*limit;
		json=JSONUtil.salesListToJson(salesService.paging(firstResult, limit));
		json="{\"code\": 0,\"msg\":\"success\",\"count\": "+totalCount+",\"data\":"+json+"}";
		return json;
	}
	
	@RequestMapping(value="viewSales")
	public String salesList(Model model,int salesid) {
		model.addAttribute("sales", salesService.findById(Sales.class, salesid));
		model.addAttribute("salesLineItem", itemService.findBySalesid(salesid));
		return "sales/view";
	}
	
	/**
	 * 更换房间,GET
	 */
	@RequestMapping(value="changeRoom",method=RequestMethod.GET)
	public String changeRoom(Model model,int itemid,String roomNo) {
		SalesLineItem item=itemService.findById(SalesLineItem.class, itemid);
		int categoryid=item.getSales().getCategory().getCategoryid();;
		model.addAttribute("roomList", roomService.findRoomByCategory(categoryid));
		model.addAttribute("availableMap", roomService.findAvailableRoomByCategory(categoryid));
		model.addAttribute("roomNo", roomNo);
		model.addAttribute("oldRoom", item.getRoom().getRoomid());
		model.addAttribute("itemid", itemid);
		return "checkin/changeRoom";
	}
	
	/**
	 * 保存更换房间
	 */
	@ResponseBody
	@RequestMapping(value="changeRoom",method=RequestMethod.POST)
	public String saveChangeRoom(int itemid,int newRoom,int oldRoom) {
		if(roomService.changeRoom(itemid, newRoom, oldRoom))
			return JSONUtil.returnSuccess();
		return JSONUtil.returnFailure();
	}
	
	/**
	 * 新增房客,GET方式
	 */
	@RequestMapping(value="addCustomer",method=RequestMethod.GET)
	public String addCustomer_GET(Model model,int itemid,int count,String roomNo) {
		model.addAttribute("itemid", itemid);
		model.addAttribute("roomNo", roomNo);
		model.addAttribute("allocated",count);//当前已入住人数，最多三人
		return "checkin/addCustomer";
	}
	
	/**
	 * 新增房客,POST方式
	 */
	@ResponseBody
	@RequestMapping(value="addCustomer",method=RequestMethod.POST)
	public String addCustomer_POST(SalesLineItem item,HttpServletRequest request) {
		String[] customerNames=request.getParameterValues("customerName");
		String[] id_numbers=request.getParameterValues("id_number");
		String[] teles=request.getParameterValues("tele");
		for(int i=0;i<item.getCount();i++) {
			ItemDescription desc=new ItemDescription();
			desc.setSalesLineItem(item);
			desc.setCustomerName(customerNames[i]);
			desc.setId_number(id_numbers[i]);
			desc.setTele(teles[i]);
			descService.save(desc);
		}
		itemService.updateCustomerCount(item.getItemid(), item.getCount());
		return JSONUtil.returnSuccess();
	}
	
	/**
	 * 查看详情
	 * 此处简单实现，与'销售记录'菜单中的查看详情页面一致
	 */
	@RequestMapping(value="viewCheckin")
	public String viewCheckin(Model model,int itemid) {
		SalesLineItem item=itemService.findById(SalesLineItem.class, itemid);
		model.addAttribute("sales", salesService.findById(Sales.class, item.getSales().getSalesid()));
		model.addAttribute("salesLineItem", itemService.findBySalesid(item.getSales().getSalesid()));
		return "sales/view";
	}
}
